#include "SocketStream.h"

SocketStream::SocketStream()
  : handle_ (INVALID_HANDLE_VALUE)
{ }

SocketStream::SocketStream(Socket h)
  : handle_ (h)
{ }

SocketStream::~SocketStream()
{
  close(handle_);
}

Socket SocketStream::getHandle() const
{
  return handle_;
}

void SocketStream::setHandle(Socket h)
{
  handle_ = h;
}

// ssize_t SocketStream::recv(void * buf, size_t len, int flags)
// {
//   return ::recv(handle_, buf, len, flags);
// }

// ssize_t SocketStream::send(const void * buf, size_t len, int flags)
// {
//   return ::send(handle_, buf, len, flags);
// }

std::string SocketStream::recv() const
{
  int len;
  ::recv(handle_, &len, sizeof len, 0);
  
  char buf[len+1];
  ::recv(handle_, &buf, len, 0);
  buf[len] = '\0';
  std::string msg(buf, len);
  
  return msg;
}

void SocketStream::send(const std::string &str)
{
  int length = str.length();
  ::send(handle_, &length, sizeof length, 0);
  ::send(handle_, str.c_str(), length, 0);
}

